package com.example.service;


import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;

public class MyWebSocketServer extends WebSocketServer {

    public MyWebSocketServer(int port) {
        super(new InetSocketAddress(8082));
    }

    WebSocket webSocketClient;

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        webSocketClient =conn;
        // 新的 WebSocket 连接已建立
        System.out.println("New connection: " + conn.getRemoteSocketAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        // WebSocket 连接已关闭
        Log.e("msg","Connection closed: "+ conn.getRemoteSocketAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        // 接收到文本消息
       Log.e("msg","Received message: " + message);
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        // 发生错误
        Log.e("msg","服务端错误了 ");
    }

    /**
     * 发送消息给当前连接客户端
     * @param msg
     */
    public void sendMsg2Client(String msg){
        webSocketClient.send(msg);
    }

    @Override
    public void onStart() {

    }
}